import { createRouter, createWebHistory } from "vue-router";

// 路由配置
const routes = [
  {
    path: "/",
    redirect: "/dashboard",
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/login/index.vue"),
    meta: { title: "登录" },
  },
  {
    path: "/dashboard",
    name: "Dashboard",
    component: () => import("../views/dashboard/index.vue"),
    meta: { title: "首页仪表盘", requiresAuth: true },
  },
  {
    path: "/member",
    name: "Member",
    component: () => import("../views/member/index.vue"),
    meta: { title: "会员管理", requiresAuth: true },
  },
  {
    path: "/coupon",
    name: "Coupon",
    component: () => import("../views/coupon/index.vue"),
    meta: { title: "优惠券管理", requiresAuth: true },
  },
  {
    path: "/order",
    name: "Order",
    component: () => import("../views/order/index.vue"),
    meta: { title: "订单管理", requiresAuth: true },
  },
  {
    path: "/reservation",
    name: "Reservation",
    component: () => import("../views/reservation/index.vue"),
    meta: { title: "预约管理", requiresAuth: true },
  },
  {
    path: "/recharge",
    name: "Recharge",
    component: () => import("../views/recharge/index.vue"),
    meta: { title: "充值管理", requiresAuth: true },
  },
  {
    path: "/voucher",
    name: "Voucher",
    component: () => import("../views/voucher/index.vue"),
    meta: { title: "团购券管理", requiresAuth: true },
  },
  {
    path: "/message",
    name: "Message",
    component: () => import("../views/message/index.vue"),
    meta: { title: "消息通知", requiresAuth: true },
  },
  {
    path: "/finance",
    name: "Finance",
    component: () => import("../views/finance/index.vue"),
    meta: { title: "财务管理", requiresAuth: true },
  },
  {
    path: "/setting",
    name: "Setting",
    component: () => import("../views/setting/index.vue"),
    meta: { title: "系统设置", requiresAuth: true },
  },
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("../views/error/404.vue"),
    meta: { title: "404" },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title
    ? `${to.meta.title} - 棋牌室管理系统`
    : "棋牌室管理系统";

  // 登录拦截
  if (to.meta.requiresAuth) {
    const token = localStorage.getItem("token");
    if (!token) {
      next({ path: "/login" });
      return;
    }
  }
  next();
});

export default router;
